package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务类，定时处理订单状态
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 定期处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void timeOutOrders(){
        log.info("定时处理超时订单："+ LocalDateTime.now());
        List<Orders> timeOutOrders = ordersMapper.getTimeOutOrders(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        //如果没有超时订单直接结束
        if (timeOutOrders==null || timeOutOrders.size()==0){
            return;
        }

        for (Orders timeOutOrder : timeOutOrders) {
            timeOutOrder.setStatus(Orders.CANCELLED);
            timeOutOrder.setCancelTime(LocalDateTime.now());
            timeOutOrder.setCancelReason("订单超时未支付");
            ordersMapper.update(timeOutOrder);
        }
    }

    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void alwaysDeliveringOrders(){
        log.info("处理一直处于派送中的订单"+LocalDateTime.now());
        List<Orders> alwaysDelivering = ordersMapper.getTimeOutOrders(Orders.DELIVERY_IN_PROGRESS,
                                                            LocalDateTime.now().plusMinutes(-60));

        //如果没有派送中订单直接结束
        if (alwaysDelivering==null || alwaysDelivering.size()==0){
            return;
        }
        for (Orders order : alwaysDelivering) {
            order.setStatus(Orders.CANCELLED);
            order.setPayStatus(Orders.REFUND);
            order.setCancelReason("订单一直处于派送中");
            order.setCancelTime(LocalDateTime.now());
        }



    }
}
